package com.workcell.workdata.im.component.message;

import com.farsunset.cim.group.TagSessionGroup;
import com.farsunset.cim.model.Message;
import com.workcell.workdata.im.component.event.TagMessageEvent;
import com.workcell.workdata.im.model.dto.TagMessage;
import com.workcell.workdata.im.util.JSON;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;


/**
 * 集群环境下，监听redis队列，广播消息到每个实例进行推送
 * 如果使用MQ的情况也，最好替换为MQ消息队列
 */
@Component
public class TagMessageListener implements MessageListener {

    @Resource
    private TagSessionGroup tagSessionGroup;

    @Override
    public void onMessage(org.springframework.data.redis.connection.Message redisMessage, byte[] bytes) {
        TagMessage tagMessage = JSON.parse(redisMessage.getBody(), TagMessage.class);
        this.handle(tagMessage);
    }

    @EventListener
    public void onMessage(TagMessageEvent event) {
        this.handle(event.getSource());
    }

    private void handle(TagMessage tagMessage){

        Message message = tagMessage.getMessage();

        tagSessionGroup.write(tagMessage.getTag(), message, Collections.singletonList(message.getSender()));

    }
}
